package toy.keli.edic.ui.home.homescreen

import android.app.Dialog
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.Icon
import androidx.compose.material.Tab
import androidx.compose.material.TabRow
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import toy.keli.edic.R
import toy.keli.edic.data.Db
import toy.keli.edic.data.GlobalVal
import toy.keli.edic.data.PreviewData
import toy.keli.edic.data.config.BookConf
import toy.keli.edic.data.local.entity.TestEntity
import toy.keli.edic.ui.home.jdc.book
import toy.keli.edic.ui.home.jdc.errorCount
import toy.keli.edic.ui.home.jdc.rightCount
import toy.keli.edic.ui.home.jdc.tIndex
import toy.keli.edic.ui.main.components.CustomIconRadioButton
import toy.keli.edic.ui.main.components.Display.mt
import toy.keli.edic.ui.main.extend.MainRun
import toy.keli.edic.ui.navigation.NavScreen
import toy.keli.edic.util.ActivityRun
import toy.keli.edic.view.skin.LayoutJdc
import toy.keli.edic.view.skin.LayoutJdc.layouts.methods.id
import java.text.SimpleDateFormat
import java.util.LinkedList
import java.util.Random

@Composable
@Preview(showBackground = true)
fun SelectWordPage(){
    val tabs = listOf("看词选义", "看义选词", "听音写词", "看图选词")
    val pageState = rememberPagerState(
        initialPage = 0,
        pageCount = { tabs.size }
    )
    val scope = rememberCoroutineScope()
    var showTitle by remember {
        book.reset()
        mutableStateOf(false)
    }
    LaunchedEffect(pageState) {
        snapshotFlow {
            // 获取当前页面、偏移量和进度
            Triple(pageState.currentPage, pageState.currentPageOffsetFraction, pageState.isScrollInProgress)
        }.collect { (page, offset, isScrolling) ->
            // 处理滑动事件
            println("当前页面: $page, 偏移量: $offset, 是否正在滑动: $isScrolling")
            // 示例：根据偏移量执行动画或其他操作
            if (isScrolling && !showTitle) {
                showTitle=true
                // 正在滑动，执行相应逻辑
            }
        }
    }
    Box  {
        AnimatedVisibility(visible = showTitle,
            enter = fadeIn(),
            exit = fadeOut()
        ) {
            TabRow(
                selectedTabIndex = pageState.currentPage,
                backgroundColor = Color.White,
                contentColor = Color.Blue,
                modifier = Modifier.padding(horizontal = 50.dp)
            ) {
                tabs.forEachIndexed { index, title ->
                    Tab(
                        text = { Text(title, fontSize = 9.sp) },
                        selected = pageState.currentPage == index,
                        onClick = {
                            scope.launch {
                                pageState.animateScrollToPage(index)
                            }
                        },
                        modifier = Modifier.padding(0.dp)
                    )
                }
            }
            MainRun(2000){
                showTitle = false
            }
        }

        // 内容区域
        HorizontalPager (
            state = pageState
        ){ page ->
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                  getIndex(page)
            }
        }
    }
}
data class Option(val name: String, val selected: MutableState<Int>,val isOk:Boolean)
@Composable
fun getIndex(selectedTabIndex: Int) {
    var wordIndex by remember { mutableStateOf(0) }
    val roSize = Math.min(3,book.size-1)
    if( LocalInspectionMode.current) {
        PreviewData.selectWordPage()
    }
    var title by remember { mutableStateOf("") }
    var status by remember { mutableStateOf("") }
    val options = remember { mutableStateListOf<Option>() }

    LaunchedEffect(wordIndex) {
        val nowWord = listOf(book.word, book.ch, mt("请根据正确的发音选择正确的词"), book.ch)
        val ro = Random().nextInt(Math.min(3,book.size-1))

        title = nowWord[selectedTabIndex]
        status ="(${book.index+1}/${book.size})"
        options.clear()
        val shuffledArray = LinkedList((0..book.size-1).toList()
            .filter { it != book.index }
            .shuffled())
        (0..roSize).forEach { i ->
            var index = if (i == ro) book.index else shuffledArray.removeFirst()
            val nowWordModel = BookConf.words[index]
            val ch =arrayListOf(nowWordModel.ch!!, nowWordModel.word, nowWordModel.word, nowWordModel.word)
            val selectedResult = mutableStateOf(0)
            options.add(Option(ch[selectedTabIndex],selectedResult,ro == i))
        }
    }
    Column(modifier = Modifier.width(IntrinsicSize.Min).padding(horizontal = 20.dp)) {
        Row (modifier = Modifier.width(IntrinsicSize.Max)){
            Icon(
                painter = painterResource(id = R.drawable.speak),
                contentDescription = null,
                modifier = Modifier
                    .size(20.dp, 20.dp)
                    .clickable { GlobalVal.tts.speak(book.word) }
            )
            Text(title, modifier = Modifier.padding(horizontal = 10.dp))
            Text(status)
        }
        options.forEach{option->
            Row(
                verticalAlignment = Alignment.CenterVertically,
                modifier = Modifier.padding(vertical = 4.dp).width(IntrinsicSize.Max)
            ) {
                CustomIconRadioButton(
                    option.name,
                    option.selected.value,
                ) {
                    val ok = option.isOk
                    LayoutJdc.playStatus(ok)
                    option.selected.value = if(ok) 1 else 2
                    if(!ok) {
                        errorCount++
                        options.forEach { if (it.isOk) it.selected.value = 1 }
                    }else{
                        rightCount++
                    }
                    MainRun(2000) {
                        if (book.next(autoReset = false)) {
                            wordIndex = book.index
                        } else {
                            resultBox(rightCount, errorCount){
                                book.reset()
                            }
                        }
                    }
                    ok
                }
            }
        }
    }
}


fun resultBox(rc: Int, ec: Int,reset:()->Unit) {
    val ct= ActivityRun.context
    val pW = LayoutInflater.from(ct).inflate(R.layout.dialog_result, null)
    val dialog = Dialog(ct)
    val starIds = listOf(R.id.start_1, R.id.start_2, R.id.start_3)
    val tsy = ct.resources.getStringArray(R.array.tsy)
    //星级
    val xn = rc*100/(rc+ec)+1
    pW.apply {
        //正确数
        findViewById<TextView>(R.id.tv_result_correct).text = rc.toString()
        //错误数
        findViewById<TextView>(R.id.tv_result_wrong).text = ec.toString()

        starIds.forEachIndexed{index,id->
            val rid = if(xn/33>index) R.drawable.star_checked else R.drawable.star_bg
            findViewById<ImageView>(id).setBackgroundResource(rid)
        }
        //描述语
        findViewById<TextView>(R.id.tv_result).text = tsy[Math.max(0,xn/10-1)]
        //单词学习
//        findViewById<Button>(R.id.btn_study_word).setOnClickListener {
//            NavScreen.openJdc(1)
//            dialog.hide()
//        }
        findViewById<Button>(R.id.btn_study_word).visibility = View.GONE
        //重新挑战
        findViewById<Button>(R.id.btn_restart).setOnClickListener {
            book.index =0
            rightCount =0
            errorCount =0
            book.next(0)
            reset()
            dialog.hide()
        }
    }

    dialog.setContentView(pW)
    dialog.show()

    var buttonTabs = listOf(R.id.btn_recite_1, R.id.btn_recite_2, R.id.btn_recite_3, R.id.btn_recite_4)
    val typeName = id<Button>(buttonTabs[tIndex]).text
    val t = System.currentTimeMillis()
    val d = SimpleDateFormat("yyyy-MM-dd HH:mm").format(t)
    GlobalScope.launch {
        Db.user.test.add(
            TestEntity(
                "正确数：$rc 错误数：$ec",
                "选词测试-$typeName-$d",
                BookConf.instance.id,
                xn / 100f,
                t
            )
        )
    }
}